const Order = require("../model/order.model");
// 使用模糊查询需要先引入Op
const seq = require("sequelize");
const Op = seq.Op;
const User = require("../model/user.model");
const Category = require("../model/category.model");

const alipaySdk = require('../utils/alipayUtil');
const AlipayFormData = require('alipay-sdk/lib/form').default;
class OrderService {
  /**
   * 创建
   * @returns {Promise<{code: string, message: string}>}
   * @param order
   */
  async createOrder(order) {
    const res = await Order.create(order);
    return res.dataValues;
  }

  /**
   * 更新
   * @param order_number
   * @param order
   * @returns {Promise<boolean>}
   */
  async updateOrder(order_number, order) {
    const res = await Order.update(order, { where: { order_number } });
    console.log(res,"res")
    return res[0] > 0;
  }

  /**
   * 删除
   * @param id
   * @returns {Promise<boolean>}
   */

  async removeOrder(id) {
    const res = await Order.destroy({ where: { id } });
    return res > 0;
  }

  /**
   * 恢复
   * @param id
   * @returns {Promise<boolean>}
   */

  async restoreOrder(id) {
    const res = await Order.restore({ where: { id } });
    return res > 0;
  }

  async findOrder({ pageNum, pageSize, title, nick_name ,user_id}) {
    const offset = (pageNum - 1) * pageSize;
    const whereOpt1 = {};
    const whereOpt2 = {};

    nick_name &&
      Object.assign(whereOpt1, {
        nick_name: {
          [Op.like]: `%${nick_name}%`,
        },
      });

    user_id && Object.assign(whereOpt1, { id: user_id });

    title &&
    Object.assign(whereOpt2, {
      title: {
        [Op.like]: `%${title}%`,
      },
    });
    const { count, rows } = await Order.findAndCountAll({
      offset: offset,
      limit: pageSize * 1,
      include: [
        {
          model: User,
          as: "user_info",
          attributes: ["nick_name"],
          where: whereOpt1,
        },
        {
          model: Category,
          as: "cat_info",
          where: whereOpt2,
        },
      ],
      order: [["createdAt", "DESC"]],
    });

    return {
      pageNum,
      pageSize,
      total: count,
      list: rows,
    };
  }

  async findOrderInfo(id) {
    const whereOpt = {};
    id && Object.assign(whereOpt, { id });

    const res = await Order.findOne({
      where: whereOpt,
    });

    return res ? res.dataValues : null;
  }

  async toPayMoney({order_number, money,cat_id}) {
    //前端给后端的数据
    //对接支付宝
    const formData = new AlipayFormData();
    formData.setMethod('get');

    formData.addField('returnUrl', `http://localhost:5173/category/category/details?id=${cat_id}&isPay=1`);
    formData.addField('bizContent', {
      outTradeNo: order_number,
      productCode: 'FAST_INSTANT_TRADE_PAY',
      totalAmount: money,
      subject: '资助',
      body: '资助项目'
    });

    return await alipaySdk.exec(
        'alipay.trade.page.pay',
        {},
        {formData: formData},
    );
  }

  async checkPayStatus({out_trade_no,trade_no}) {
    //对接支付宝
    const formData = new AlipayFormData();
    formData.setMethod('get');
    formData.addField('bizContent', {
      out_trade_no,
      trade_no
    });

    return await alipaySdk.exec(
        'alipay.trade.query',
        {},
        {formData: formData},
    );
  }

}

module.exports = new OrderService();
